package cn.monkey.family.server.domain.shop.item;

import cn.monkey.family.data.Result;
import cn.monkey.family.data.Results;
import cn.monkey.family.data.context.RequestContext;
import cn.monkey.family.data.crud.AbstractCrudService;
import cn.monkey.family.data.shop.item.*;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Optional;

@Service
public class ItemService extends AbstractCrudService<String, ItemQueryRequest, Item, ItemDto, ItemVo, ItemMapper, ItemRepository>
        implements IItemService {

    protected final BeforeItemDeleteEventListener beforeItemDeleteEventListener;

    public ItemService(ItemRepository repository, ItemMapper mapper, BeforeItemDeleteEventListener beforeItemDeleteEventListener) {
        super(repository, mapper);
        this.beforeItemDeleteEventListener = beforeItemDeleteEventListener;
    }

    @Override
    public Result<Void> delete(RequestContext requestContext, String s) {
        Optional<Item> itemOptional = this.repository.findById(s);
        if (itemOptional.isEmpty()) {
            return Results.notFound();
        }
        Result<Void> result = this.beforeItemDeleteEventListener.beforeItemDelete(requestContext, itemOptional.get());
        if (!Results.isOk(result)) {
            return Results.fromFailOrError(result);
        }
        this.repository.deleteById(s);
        return Results.ok();
    }

    /**
     * 根据createdTime 取最近几条,其他传来的排序参数不变
     */
    @Override
    public Result<Collection<ItemVo>> readBanner(RequestContext requestContext, ItemQueryRequest queryRequest, Pageable pageable) {
        PageRequest pageRequest = PageRequest.of(0, pageable.getPageSize(), pageable.getSort().and(Sort.by(Sort.Direction.DESC, "createdTime")));
        Result<Page<ItemVo>> pageResult = this.readPage(requestContext, queryRequest, pageRequest);
        return pageResult.map(Slice::getContent);
    }
}
